package com.xk857.service.impl;

import com.xk857.entities.SysMenu;
import com.xk857.entities.SysUser;
import com.xk857.feign.IFeignSystemController;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author CV大魔王
 * @Description
 * @date 2021/2/26 21:38
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private IFeignSystemController feignSystemController;

    /**
     * 加载用户对象
     * @param username 前端传递过来的账号
     * @return UserDetails对象
     * @throws UsernameNotFoundException 抛出异常
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 1.判斷用戶名是否为空
        if (StringUtils.isEmpty(username)) {
            throw new BadCredentialsException("用户名不能为空");
        }

        // 2.通过用户名查询数据库中的用户信息
        SysUser sysUser = feignSystemController.findUserByUsername(username);
        if (sysUser == null) {
            throw new BadCredentialsException("用户名或密码错误");
        }

        // 3.通过用户id查询用户权限信息
        List<SysMenu> menuList = feignSystemController.findMenuByUserId(sysUser.getId());

        // 4.封装权限信息
        List<GrantedAuthority> authorities = null;
        if (CollectionUtils.isNotEmpty(menuList)) {
            authorities = new ArrayList<>();
            for (SysMenu sysMenu : menuList) {
                String code = sysMenu.getCode();
                authorities.add(new SimpleGrantedAuthority(code));
            }
        }
        // 5.构建UserDetails接口的实现类JwtUser对象
        return new JwtUser(sysUser.getId(), sysUser.getUsername(), sysUser.getPassword(), sysUser.getNickName(), sysUser.getImageUrl(), sysUser.getMobile(), sysUser.getEmail(), sysUser.getIsAccountNonExpired(), sysUser.getIsAccountNonLocked(), sysUser.getIsCredentialsNonExpired(), sysUser.getIsEnabled(), authorities);
    }
}
